package com.jy.oms.framework.thread;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.annotation.Selector;
import org.springframework.boot.actuate.endpoint.annotation.WriteOperation;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Map;

/**
 * 线程池状态监控
 *
 * @author liuquan
 */
@Endpoint(id = "/thread/endpoint")
@Component
public class ThreadPoolEndpoint {

    @Autowired
    private ThreadPoolManager threadPoolManager;

    /**
     * 查看所有线程池状态
     */
    @ReadOperation
    public Map<String, ThreadPoolStatus> status() {
        return threadPoolManager.getThreadPoolStatus();
    }

    /**
     * 查看指定线程池状态
     */
    @ReadOperation
    public ThreadPoolStatus singleStatus(@Selector String threadPoolKey) {
        Map<String, ThreadPoolStatus> threadPoolStatusMap = threadPoolManager.getThreadPoolStatus();
        return threadPoolStatusMap.get(threadPoolKey);
    }

    /**
     * 动态修改线程池参数
     *
     * @param threadPoolKey   线程池key
     * @param corePoolSize    核心线程池数
     * @param maximumPoolSize 最大线程数
     */
    @WriteOperation
    public void configureThreadPool(@Selector String threadPoolKey,
                                    @Nullable Integer corePoolSize,
                                    @Nullable Integer maximumPoolSize) {
        Assert.notNull(threadPoolKey, "线程池key不能为空");
        Assert.notNull(corePoolSize, "核心线程池数不能为空");
        Assert.notNull(maximumPoolSize, "最大线程数不能为空");
        Assert.isTrue(corePoolSize <= maximumPoolSize, "核心线程池数必须小于等于最大线程数");
        threadPoolManager.configureThreadPool(threadPoolKey, corePoolSize, maximumPoolSize);
    }
}
